package com.wnxy.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wnxy.dto.LoginDto;
import com.wnxy.dto.ManagerDetail;
import com.wnxy.dto.Result;
import com.wnxy.dto.StatusCode;
import com.wnxy.mapper.ManagerMapper;
import com.wnxy.model.Manager;
import com.wnxy.service.ManagerService;
import com.wnxy.service.RoleService;
import com.wnxy.util.BeanCopyUtil;
import com.wnxy.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//@Component
public class SuccessHandler implements AuthenticationSuccessHandler {
    private ObjectMapper om=new ObjectMapper();
//    @Autowired
//    private ManagerService managerService;
    private ManagerService managerService;

    public SuccessHandler(ManagerService managerService) {
        this.managerService = managerService;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        Result result = Result.getInstance().setFlag(true).setStatusCode(StatusCode.SUCCESS.getCode()).setMessage("登陆成功");
        ManagerDetail manger = (ManagerDetail) authentication.getPrincipal();
        System.out.println(manger);
        manger.setManagerPassword(null);
        LoginDto ld = BeanCopyUtil.copyProperties(manger, LoginDto.class);
        ld.setManagerLogintime(DateUtil.parseDateLong(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss"));
        result.setData(ld);
        //redis存入
        System.out.println(managerService);
        managerService.loadRolePath();
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf8");
        response.getWriter().write(om.writeValueAsString(result));
        response.getWriter().flush();
    }
}
